package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl;

import java.util.Objects;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.iwhalecloud.citybrain.flow.platform.manager.application.common.context.ModelDeploymentContext;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.ModelDeploymentPostProcessor;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.FlowModelVariableVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowModelVariableRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Processor - 保存模型变量
 *
 * @author lilh
 * @date 2021/4/26 14:32
 */
@Component
public class SaveModelVariablesProcessor implements ModelDeploymentPostProcessor {

    @Autowired
    private FlowModelVariableRepository flowModelVariableRepository;

    @Override
    public void process(ModelDeploymentContext context) {
        saveModelVariable(context.getDeployId(), context.getModelId(), context.getModelJson());
    }

    private void saveModelVariable(String deployId, String modelId, JsonNode modelJson) {
        ObjectNode properties = (ObjectNode) modelJson.get("properties");
        JsonNode modelVariables = properties.get("modelVariables");
        if (Objects.isNull(modelVariables)) {
            return;
        }

        ArrayNode arrayNode = (ArrayNode) modelVariables;
        for (JsonNode entry : arrayNode) {
            FlowModelVariableVo variableEntity = new FlowModelVariableVo();
            variableEntity.setModelId(modelId);
            variableEntity.setDeployId(deployId);
            variableEntity.setName(entry.get("name").asText());
            variableEntity.setCode(entry.get("code").asText());
            variableEntity.setType(entry.get("type").asText());

            JsonNode defaultValue = entry.get("defaultValue");
            if (Objects.nonNull(defaultValue)) {
                variableEntity.setDefaultValue(defaultValue.asText());
            }
            JsonNode description = entry.get("description");
            if (Objects.nonNull(description)) {
                variableEntity.setDescription(description.asText());
            }
            flowModelVariableRepository.insertModelVariable(variableEntity);
        }
    }
}
